/**
 * 以数组形式表示多边形和三角形
 * @param {*} polygon 
 */

function getPolygon (polygon) {
    var result = new Array();
    var length = polygon.length;
    var num = (length+1)/2;
    for (var i=0;i<= num-1;i++) {
        var j= (i+1)*2-1;
        result[i] = new Array();
        result[i][0] = polygon[j-1];
        result[i][1] = polygon[j];
    }
    return result;
}
function getTriangles (pg,trianglesIndex) {
    var result = new Array();
    var indexLength = trianglesIndex.length;
    var index = (indexLength+1)/3;
    for (var i=0; i<=index-1; i++) {
        var j = (i+1)*3-1;
        
        result[i] = new Array();

        result[i][0] = new Array();
        // console.log("indext : ",trianglesIndex[j-2]);
        // console.log("pg x : ",pgtrianglesIndex[j-2]);
        result[i][0][0] = pg[trianglesIndex[j-2]][0];
        result[i][0][1] = pg[trianglesIndex[j-2]][1];

        result[i][1] = new Array();
        result[i][1][0] = pg[trianglesIndex[j-1]][0];
        result[i][1][1] = pg[trianglesIndex[j-1]][1];

        result[i][2] = new Array();
        result[i][2][0] = pg[trianglesIndex[j]][0];
        result[i][2][1] = pg[trianglesIndex[j]][1];
    }    
    return result;
}
/**
 * 在多边形中，根据面积选择三角形
 */
function generateDistribution(triangles) {
    const totalArea = triangles.reduce((sum, triangle) => sum + getTriangleArea(triangle), 0);
    // console.log("total : ",totalArea);
    const cumulativeDistribution = [];
    
    for (let i = 0; i < triangles.length; i++) {
      const lastValue = cumulativeDistribution[i - 1] || 0;
      const nextValue = lastValue + getTriangleArea(triangles[i]) / totalArea;
      cumulativeDistribution.push(nextValue);
    }
    // [area1, area1 + aera2, area1 + area2 + area3, ...]
    return cumulativeDistribution;
}
function getTriangleArea (triangle) {
    var result;

    var a = getA(triangle[0],triangle[1]);
    var b = getA(triangle[1],triangle[2]);
    var c = getA(triangle[0],triangle[2]);
    result = Math.sqrt((a+b+c)*(a+b-c)*(a+c-b)*(b+c-a));
    return result;
}
function getA(x,y) {
    return Math.sqrt(Math.abs(x[0]*x[0]+y[0]*y[0]));
}

function selectRandomTriangle(triangles) {
    const cumulativeDistribution = generateDistribution(triangles);
    // console.log("cumulative : ",cumulativeDistribution);
    const rnd = Math.random();
    // console.log("rnd : ",rnd);
    const index = cumulativeDistribution.findIndex(v => v > rnd);
    
    return triangles[index];
}

/**
 * 在三角形中随机生成点
 */

function calcRandomPoint(triangle) {
    let wb = Math.random();
    let wc = Math.random();
  
    // point will be outside of the triangle, invert weights
    if (wb + wc > 1) {
      wb = 1 - wb;
      wc = 1 - wc;
    }
  
    const [a, b, c] = triangle.map(coords => ({x: coords[0], y: coords[1]}));
  
    const rb_x = wb * (b.x - a.x);
    const rb_y = wb * (b.y - a.y);
    const rc_x = wc * (c.x - a.x);
    const rc_y = wc * (c.y - a.y);
  
    const r_x = rb_x + rc_x + a.x;
    const r_y = rb_y + rc_y + a.y;
  
    return [r_x, r_y]
}

/**
 * 画图 多边形和点
 */

function drawPolygon(context,polygon, color, fill) {
    context.beginPath();

    context.strokeStyle = color;
    if (fill && fill !== true) context.fillStyle = fill;

    if (typeof polygon[0][0] === 'number') polygon = [polygon];

    for (var k = 0; k < polygon.length; k++) {
        var points = polygon[k];
        for (var i = 0; i < points.length; i++) {
            var x = points[i][0],
                y = points[i][1];
            if (i === 0) context.moveTo(x, y);
            else context.lineTo(x, y);
        }
        if (fill) context.closePath();
    }
    context.stroke();

    if (fill && fill !== true) context.fill('evenodd');
}

function drawPoint (context,numberOfPoints,triangles) {
    for (let i=0;i<numberOfPoints;i++){
        const randomTriangle = selectRandomTriangle(triangles);
        const randomPoint = calcRandomPoint(randomTriangle);
    
        context.beginPath();
        context.arc(...randomPoint,2,0,Math.PI*2);
        context.fill();
    }
}